package com.htx.zqs.blesmartmask.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.gyf.barlibrary.ImmersionBar;
import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.EventBean;
import com.htx.zqs.blesmartmask.broadcastreceiver.NetworkChange;
import com.htx.zqs.blesmartmask.eventbus.BleDataEvent;
import com.htx.zqs.blesmartmask.listeners.BleNotifyListener;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.utils.AlertUtils;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.BleUtils;
import com.htx.zqs.blesmartmask.utils.Constants;
import com.htx.zqs.blesmartmask.utils.EventBusUtil;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.ScreenManager;
import com.htx.zqs.blesmartmask.utils.Utils;
import com.noober.background.BackgroundLibrary;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.HashMap;

import timber.log.Timber;

/**
 * Created by zhao on 2018/5/11.
 */

public class BaseActivity extends FragmentActivity {

    public Activity activity;
    public ImmersionBar mImmersionBar;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenManager.setDefault(this);
        BackgroundLibrary.inject(this);
        activity = this;
        initStatusBar();

        MobclickAgent.setDebugMode(true);
        UMConfigure.setLogEnabled(true);

        //新建的Activity加入栈
        MyApplication.getActivityManager().pushActivity(this);
    }


    public void initStatusBar() {
        mImmersionBar = ImmersionBar.with(this)
                .keyboardEnable(true)
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//        mImmersionBar
//
//                .transparentNavigationBar()
//                //.titleBar(R.id.chart1)
//                .fitsSystemWindows(true)
//                .fullScreen(false)
//                .statusBarAlpha(0.2f)
//                .navigationBarAlpha(0.3f)
//                .statusBarColor(R.color.smartmask)
//        .navigationBarColor(R.color.smartmask);//使用该属性,必须指定状态栏颜色
        mImmersionBar.init();   //所有子类都将继承这些相同的属性
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.setCatchUncaughtExceptions(true);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        MobclickAgent.setCatchUncaughtExceptions(true);
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null) {
            mImmersionBar.destroy(); //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
        }
        MyApplication.getActivityManager().popActivity(this);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 235:
                if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0] == PermissionChecker.PERMISSION_GRANTED) {
                    // 已授权

                } else {
                    // 未授权

                }

                break;
        }
    }

    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    public void startNotify(final BleDevice bleDevice) {
        BleDevice firstBleDevice = Utils.getFirstDevice();
        if (firstBleDevice == null) return;
        if (!TextUtils.equals(bleDevice.getMac(), firstBleDevice.getMac())) {
            //确保只有一台设备在接收硬件信息
            return;
        }
        BleUtils.notify(bleDevice, new BleNotifyListener() {
            @Override
            public void onSuccess(byte[] buffer) {
                String strData = new String(buffer);
                int[] intArray = new int[buffer.length];
                for (int i = 0; i < intArray.length; i++) {
                    intArray[i] = (buffer[i] & 0xff);
                }
                //验证
                if (strData.startsWith("ATN")) {
                    MyApplication.bluetoothState = Contants.STATE_NO_RUN;
                }
                //油水
                if (strData.startsWith("AT-C")) {
                    setWaterData(bleDevice, buffer);
                }
                //获取设备使用时间、次数
                if (strData.startsWith("AT-M")) {
                    setWaterData(bleDevice, buffer);
                }
                //面膜
                if (strData.startsWith("ATJ")) {
                    int state = intArray[11];
                    MyApplication.state = state;
                    int index = intArray[4] * 256 * 256 + intArray[5] * 256 + intArray[6];
                    if (state != 0) {
                        MyApplication.runningIndex = index;
                    } else {
                        MyApplication.runningIndex = 100000;
                    }

                    setCourseData(bleDevice, buffer);
                }

                String hexData = Utils.bytesToHexString(new byte[]{buffer[2]});
                if (hexData.contains("4a")) {
                    //设备电量更新
                    EventBus.getDefault().post(new EventBean<>(Constants.EVENT_REFRESH_ELECTRIC,
                            new BleDataEvent(bleDevice, buffer)));

                    //休眠
                    Utils.showSleepDialog(buffer[16]);
                }
            }
        });
    }

    public void setWaterData(BleDevice bleDevice, byte[] buffer) {

    }

    public void setTimesData(BleDevice bleDevice, byte[] buffer) {

    }

    public void setCourseData(BleDevice bleDevice, byte[] buffer) {
        int[] intArray = new int[buffer.length];
        for (int i = 0; i < intArray.length; i++) {
            intArray[i] = buffer[i] & 0xff;
        }
        String timeText = Utils.formatTime(intArray[7] + intArray[8], intArray[9]);
        if (timeText.equals(Constants.COURSE_END_TIME)) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Utils.EndCourse();
                }

            }, 1000);
        }
    }

    public void testWater() {
        final BleDevice bleDevice = Utils.getFirstDevice();
        if (bleDevice == null) {
            //当前没有连接ble
            AlertUtils.showAlertDialog(activity, R.string.blebroadcast_title, R.string.
                            cancel1, R.string.main_bluetooth_go, getString(R.string.blebroadcast_message),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();
                        }
                    });
            return;
        }

        BleUtils.write(bleDevice, BleUtils.getTestWaterCommand(Contants.
                TEST_DURATION), new
                BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        Timber.d("油水测试数据发送成功 mac:" + bleDevice.getMac());
                        SPUtil.put(activity, "isNeedNetData",
                                true, "isNeedNetData");
                        startNotify(bleDevice);
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {
                        Toast.makeText(activity, getResources().
                                getString(R.string.fail_test_water), Toast.LENGTH_SHORT).show();
                    }
                });
    }

}
